package com.grademaster.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grademaster.common.R;
import com.grademaster.dto.LoginRecordDto;
import com.grademaster.entity.LoginRecords;
import com.grademaster.mapper.LoginRecordsMapper;
import com.grademaster.service.LoginRecordsService;
import com.grademaster.util.LoginUtil;
import com.grademaster.util.StringUtils;
import com.grademaster.vo.LoginRecordVO;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.Instant;
import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 * @description 针对表【login_records(登录记录表)】的数据库操作Service实现
 * @createDate 2024-06-25 13:57:04
 */
@Service
public class LoginRecordsServiceImpl extends ServiceImpl<LoginRecordsMapper, LoginRecords>
        implements LoginRecordsService {

    @Autowired
    private LoginRecordsMapper loginRecordsMapper;

    /**
     * 根据分页条件查询所有登录记录
     *
     * @param loginRecordDto
     * @return
     */
    @Override
    public R getAllLoginRecordsByPage(LoginRecordDto loginRecordDto) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()) {
            return R.error("权限不足");
        }
        System.out.println(loginRecordDto.getStartTime());
        Date startTime = null;
        Date endTime = null;
        if (StringUtils.isNotEmpty(loginRecordDto.getStartTime())){
            Instant startinstant = Instant.parse(loginRecordDto.getStartTime());
            startTime = Date.from(startinstant);
            Instant endinstant = Instant.parse(loginRecordDto.getEndTime());
            endTime = Date.from(endinstant);
        }

        //查询所有登录记录
        List<LoginRecordVO> voList = loginRecordsMapper.selectLoginRecordsByConditions(
                loginRecordDto.getUsername(),
                loginRecordDto.getName(),
                loginRecordDto.getRoleName(),
                startTime,
                endTime,
                loginRecordDto.getPage(),
                loginRecordDto.getPageSize()
        );
        int count = loginRecordsMapper.countLoginRecordsByConditions(
                loginRecordDto.getUsername(),
                loginRecordDto.getName(),
                loginRecordDto.getRoleName(),
                startTime,
                endTime
        );
        Page<LoginRecordVO> page = new Page<>(loginRecordDto.getPage(), loginRecordDto.getPageSize(),count);
        page.setRecords(voList);
        return R.success(page);
    }

    /**
     * 根据分页条件查询所有登录记录
     *
     * @param loginRecordDto
     * @return
     */
    @Override
    public ResponseEntity exportExcel(LoginRecordDto loginRecordDto) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()) {
            return ResponseEntity.badRequest().build();
        }
        System.out.println(loginRecordDto.getStartTime());
        Date startTime = null;
        Date endTime = null;
        if (StringUtils.isNotEmpty(loginRecordDto.getStartTime())){
            Instant startinstant = Instant.parse(loginRecordDto.getStartTime());
            startTime = Date.from(startinstant);
            Instant endinstant = Instant.parse(loginRecordDto.getEndTime());
            endTime = Date.from(endinstant);
        }

        //查询所有登录记录
        List<LoginRecordVO> voList = loginRecordsMapper.selectLoginRecordsByConditions(
                loginRecordDto.getUsername(),
                loginRecordDto.getName(),
                loginRecordDto.getRoleName(),
                startTime,
                endTime,
                1,
                2000
        );
        Workbook workbook = new XSSFWorkbook();

        // Create a sheet named "Login Records"
        Sheet sheet = workbook.createSheet("Login Records");

        // Create header row
        Row headerRow = sheet.createRow(0);
        String[] headers = {"记录ID", "用户名", "姓名", "角色", "登录时间", "IP地址", "设备", "状态"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // Create data rows
        int rowNum = 1;
        for (LoginRecordVO record : voList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(record.getRecordId());
            row.createCell(1).setCellValue(record.getUsername());
            row.createCell(2).setCellValue(record.getName());
            row.createCell(3).setCellValue(record.getRoleName());
            row.createCell(4).setCellValue(record.getTime().toString()); // Assuming Date is converted to String
            row.createCell(5).setCellValue(record.getIpAddress());
            row.createCell(6).setCellValue(record.getDevice());
            row.createCell(7).setCellValue(record.getStatus());
        }

        // Auto-size columns (optional)
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }
        // Write workbook to ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // Create InputStreamResource to wrap ByteArrayInputStream
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        InputStreamResource resource = new InputStreamResource(inputStream);

        // Set response headers
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=courses.xlsx");

        // Return ResponseEntity with Excel file as body
        return ResponseEntity.ok()
                .headers(httpHeaders)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
}




